package com.chuji.crmcj.act;

import android.graphics.Color;
import android.graphics.drawable.PaintDrawable;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.android.volley.Response;
import com.chuji.crmcj.R;
import com.chuji.crmcj.adapter.FirstClassAdapter;
import com.chuji.crmcj.adapter.SecondClassAdapter;
import com.chuji.crmcj.adapter.downListAdapter;
import com.chuji.crmcj.bean.CarColorInfo;
import com.chuji.crmcj.bean.CarConfigureInfo;
import com.chuji.crmcj.bean.CarModelInfo;
import com.chuji.crmcj.bean.CarStockInfo;
import com.chuji.crmcj.bean.FirstClassItem;
import com.chuji.crmcj.bean.KeyPointStockInfo;
import com.chuji.crmcj.bean.SecondClassItem;
import com.chuji.crmcj.utils.SPUtils;
import com.chuji.crmcj.utils.ScreenUtils;
import com.chuji.crmcj.utils.UIUtils;
import com.chuji.crmcj.utils.UrlUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CarTypeStockActivity extends BaseActivity implements View.OnClickListener {
    //
    RelativeLayout Rl_main;
    LinearLayout ll_sum;
    //返回
    private ImageView mIv_Back;
    //汽车类型网络存储
    List<CarModelInfo.ApiParamObjEntity> mCalModelInfo;
    //汽车类型数据
    private CarModelInfo carModelInfo;
    //汽车颜色网络存储
    List<CarColorInfo.ApiParamObjEntity> carColorData;
    //汽车颜色数据
    private CarColorInfo carColorInfo;
    //汽车配置网络存储
    List<CarConfigureInfo.ApiParamObjEntity> carConfigureData;
    //汽车配置数据
    private CarConfigureInfo carConfigureInfo;
    //重点库存网络存储
    List<KeyPointStockInfo.ApiParamObjEntity> keyPointStockData;
    //重点库存数据
    private KeyPointStockInfo keyPointStockInfo;
    //全部车型
    private RelativeLayout mRl_car_sort;
    private TextView mTv_category;
    //全部配置
    private RelativeLayout mRl_cus_sort;
    private TextView mTv_cus_sort;
    //高级筛选
    private RelativeLayout mRl_time_sort;
    private TextView mTv_time_sort;
    //数目
    private TextView mTv_number;
    //显示列表
    private ListView mLv_car_stock;
    //显示下拉列表
    private PopupWindow popupwindow;

    private TextView mTvCar;
    private TextView mTvCus;
    private TextView mTvTime;

    private ImageView mIv_icon1;
    private ImageView mIv_icon2;
    private ImageView mIv_icon3;
    private PopupWindow mPwCarModel;
    //车型
    private String carModel = "";
    //配置
    private String carConfigure = "";
    //高级
    private String highDress = "";
    //popuwindow的宽度
    private int width;
    /**
     * 左侧一级分类的数据
     */
    private List<FirstClassItem> firstList;
    /**
     * 右侧二级分类的数据
     */
    private List<SecondClassItem> secondList;
    ArrayList<SecondClassItem> secondList1;
    /**
     * 使用PopupWindow显示一级分类和二级分类
     */
    private PopupWindow popupWindow;
    //全部配置
    private PopupWindow popupConfigure;
    /**
     * 左侧和右侧两个ListView
     */
    private ListView leftLV, rightLV;
    //弹出PopupWindow时背景变暗
    private View darkView;
    ListView lv;
    //弹出PopupWindow时，背景变暗的动画
    private Animation animIn, animOut;
    //公司ID
    String CompanyID = null;
    //车型ID
    String CarModelID = null;
    //汽车颜色ID
    String CarColorID = null;
    //配置ID
    String CarConfigurationID = null;
    ArrayList<SecondClassItem> secondList2;
    //选中的状态
    String state = null;
    //库存数目网络存储
    List<CarStockInfo.ApiParamObjEntity> carStockData;
    //库存数目
    private CarStockInfo carStockInfo;

    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_car_type_stock);
        Rl_main = (RelativeLayout) findViewById(R.id.Rl_main);
        ll_sum = (LinearLayout) findViewById(R.id.ll_sum);
        mIv_Back = (ImageView) findViewById(R.id.iv_Back);
        mRl_car_sort = (RelativeLayout) findViewById(R.id.rl_car_sort);
        mTv_category = (TextView) findViewById(R.id.tv_category);
        mRl_cus_sort = (RelativeLayout) findViewById(R.id.rl_cus_sort);
        mTv_cus_sort = (TextView) findViewById(R.id.tv_cus_sort);
        mRl_time_sort = (RelativeLayout) findViewById(R.id.rl_time_sort);
        mTv_time_sort = (TextView) findViewById(R.id.tv_time_sort);
        mTv_number = (TextView) findViewById(R.id.tv_number);
        mLv_car_stock = (ListView) findViewById(R.id.lv_car_stock);
        mTvCar = (TextView) findViewById(R.id.tv_category);
        mTvCus = (TextView) findViewById(R.id.tv_cus_sort);
        mTvTime = (TextView) findViewById(R.id.tv_time_sort);

        mIv_icon1 = (ImageView) findViewById(R.id.iv_icon1);
        mIv_icon2 = (ImageView) findViewById(R.id.iv_icon2);
        mIv_icon3 = (ImageView) findViewById(R.id.iv_icon3);
        //设置点击事件
        mIv_Back.setOnClickListener(this);
        mRl_car_sort.setOnClickListener(this);
        mRl_cus_sort.setOnClickListener(this);
        mRl_time_sort.setOnClickListener(this);
        /*测量拿到宽*/
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        width = metric.widthPixels;
        //得到CompanyID
        CompanyID = SPUtils.getString(UIUtils.getContext(), "CompanyID", "");
        findView();
        initDa();
        //请求车型
        reqCallCarModel();
        //请求配置
        reqCallConfigureInfo();
        //高级筛选
        initPopup();
        //全部配置
        initPopupConfigure();
        //请求重点库存
        reqKeyStockInfo();
    }

    //选中车型
    private void initPopupConfigure() {
        popupConfigure = new PopupWindow(this);
        View view = LayoutInflater.from(this).inflate(R.layout.pop_view_stock, null);
        mLv_car_stock = (ListView) view.findViewById(R.id.lv_stock);
        popupConfigure.setContentView(view);
        popupConfigure.setBackgroundDrawable(new PaintDrawable());
        popupConfigure.setFocusable(true);
        popupConfigure.setHeight(mLv_car_stock.getHeight());
        popupConfigure.setWidth(ScreenUtils.getScreenW(this));
        popupConfigure.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                darkView.startAnimation(animOut);
                darkView.setVisibility(View.GONE);
                mLv_car_stock.setSelection(0);
                mTvCus.setTextColor(UIUtils.getColor(R.color.font3));
                mIv_icon2.setImageDrawable(UIUtils.getDrawable(R.drawable.icondown));
            }
        });
    }

    private void findView() {
        darkView = findViewById(R.id.main_darkview);
        darkView.setAlpha(0.5f);
        animIn = AnimationUtils.loadAnimation(this, R.anim.fade_in_anim);
        animOut = AnimationUtils.loadAnimation(this, R.anim.fade_out_anim);
    }

    private void initDa() {
        firstList = new ArrayList<FirstClassItem>();
        //1
        secondList1 = new ArrayList<SecondClassItem>();
        secondList1.add(new SecondClassItem(0, "在库"));
        secondList1.add(new SecondClassItem(1, "在途"));
        firstList.add(new FirstClassItem(0, "状态", secondList1));
        //2
        secondList2 = new ArrayList<SecondClassItem>();
        String strURL = String.format(UrlUtils.GET_CAR_COLOR + "&CompanyID=%s", CompanyID);
        volleyRequest(strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                carColorInfo = JSON.parseObject(s, CarColorInfo.class);
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        carColorData = new ArrayList<CarColorInfo.ApiParamObjEntity>();
                        if (carColorInfo.getApiParamObj().size() != 0) {
                            for (int i = 0; i < carColorInfo.getApiParamObj().size(); i++) {
                                carColorData.add(carColorInfo.getApiParamObj().get(i));
                                secondList2.add(new SecondClassItem(i, carColorInfo.getApiParamObj().get(i).getCarColor()));
                                mColorIdDatas.add(carColorInfo.getApiParamObj().get(i).getCarColorID());
                            }
                        }
                    }
                });
            }
        });
        firstList.add(new FirstClassItem(1, "颜色", secondList2));
        firstList.addAll(firstList);
    }

    private void initPopup() {
        popupWindow = new PopupWindow(this);
        View view = LayoutInflater.from(this).inflate(R.layout.popup_layout, null);
        leftLV = (ListView) view.findViewById(R.id.pop_listview_left);
        rightLV = (ListView) view.findViewById(R.id.pop_listview_right);
        popupWindow.setContentView(view);
        popupWindow.setBackgroundDrawable(new PaintDrawable());
        popupWindow.setFocusable(true);
        popupWindow.setHeight(ScreenUtils.getScreenH(this) * 2 / 3);
        popupWindow.setWidth(ScreenUtils.getScreenW(this));
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                darkView.startAnimation(animOut);
                darkView.setVisibility(View.GONE);
                leftLV.setSelection(0);
                rightLV.setSelection(0);
                mTvTime.setTextColor(UIUtils.getColor(R.color.font3));
                mIv_icon3.setImageDrawable(UIUtils.getDrawable(R.drawable.icondown));
            }
        });
        //为了方便扩展，这里的两个ListView均使用BaseAdapter.如果分类名称只显示一个字符串，建议改为ArrayAdapter.
        //加载一级分类
        final FirstClassAdapter firstAdapter = new FirstClassAdapter(this, firstList);
        leftLV.setAdapter(firstAdapter);

        //加载左侧第一行对应右侧二级分类
        secondList = new ArrayList<SecondClassItem>();
        secondList.addAll(firstList.get(0).getSecondList());
        final SecondClassAdapter secondAdapter = new SecondClassAdapter(this, secondList);
        rightLV.setAdapter(secondAdapter);
        //左侧ListView点击事件
        leftLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //二级数据
                List<SecondClassItem> list2 = firstList.get(position).getSecondList();
//                //如果没有二级类，则直接跳转
//                if (list2 == null || list2.size() == 0) {
//                    popupWindow.dismiss();
//
//                    int firstId = firstList.get(position).getId();
//                    String selectedName = firstList.get(position).getName();
//                    handleResult(firstId, -1, selectedName);
//                    return;
//                }
                FirstClassAdapter adapter = (FirstClassAdapter) (parent.getAdapter());
                //如果上次点击的就是这一个item，则不进行任何操作
                if (adapter.getSelectedPosition() == position) {
                    return;
                }

                //根据左侧一级分类选中情况，更新背景色
                adapter.setSelectedPosition(position);
                adapter.notifyDataSetChanged();

                //显示右侧二级分类
                updateSecondListView(list2, secondAdapter);
            }
        });

        //右侧ListView点击事件
        rightLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //关闭popupWindow，显示用户选择的分类
                popupWindow.dismiss();

                int firstPosition = firstAdapter.getSelectedPosition();
                int firstId = firstList.get(firstPosition).getId();
                int secondId = firstList.get(firstPosition).getSecondList().get(position).getId();
                String selectedName = firstList.get(firstPosition).getSecondList().get(position).getName();
                mTvTime.setText(selectedName);
                handleResult(firstId, secondId, selectedName);
            }
        });
    }

    //顶部第一个标签的点击事件
    private void tab1OnClick() {
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();

        } else {
            popupWindow.showAsDropDown(findViewById(R.id.rl_car_sort));
            popupWindow.setAnimationStyle(-1);
            //背景变暗
            darkView.startAnimation(animIn);
            darkView.setVisibility(View.VISIBLE);
            darkView.setAlpha(0.5f);
        }
    }

    //刷新右侧ListView
    private void updateSecondListView(List<SecondClassItem> list2,
                                      SecondClassAdapter secondAdapter) {
        secondList.clear();
        secondList.addAll(list2);
        secondAdapter.notifyDataSetChanged();
    }

    //处理点击结果
    private void handleResult(int firstId, int secondId, String selectedName) {
        if (selectedName == "在库") {
            state = "1";
            //请求库存
            if (CarModelID != null && CarConfigurationID != null && CarColorID != null) {
                reqCarStockNum(CompanyID, CarModelID, CarColorID, CarConfigurationID, "1");
            }
        } else if (selectedName == "在途") {
            state = "0";
            //请求库存
            if (CarModelID != null && CarConfigurationID != null && CarColorID != null) {
                reqCarStockNum(CompanyID, CarModelID, CarColorID, CarConfigurationID, "0");
            }
        } else {
            reqCarStockNum(CompanyID, CarModelID, CarColorID, CarConfigurationID, "0");
        }
    }

    //请求车型网络数据
    private void reqCallCarModel() {
        String strURL = String.format(UrlUtils.GetCarModelByCompanyID + "&CompanyID=%s", CompanyID);
        volleyRequest(strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                carModelInfo = JSON.parseObject(s, CarModelInfo.class);
                mCalModelInfo = new ArrayList<CarModelInfo.ApiParamObjEntity>();
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        if (carModelInfo.getApiParamObj().size() != 0) {
                            for (int i = 0; i < carModelInfo.getApiParamObj().size(); i++) {
                                mCalModelInfo.add(carModelInfo.getApiParamObj().get(i));
                                mDatas.add(carModelInfo.getApiParamObj().get(i).getCarModel());
                                mTypeIdDatas.add(carModelInfo.getApiParamObj().get(i).getCarModelID());
                            }
                        }
                    }
                });
            }
        });
    }

    public void reqCarStockNum(String CompanyID, String CarModelID, String CarColorID, String CarConfigurationID, String state) {
        String strURL = String.format(UrlUtils.GET_CAR_STOCK_NUM + "&CompanyID=" + CompanyID + "&CarModelID=" + CarModelID + "&CarColorID=" + CarColorID + "&CarModelID=" + CarConfigurationID + "&State=" + state);
        volleyRequest(strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                carStockInfo = JSON.parseObject(s, CarStockInfo.class);
                carStockData = new ArrayList<CarStockInfo.ApiParamObjEntity>();
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        if (carStockInfo.getApiParamObj().size() != 0) {
                            for (int i = 0; i < carStockInfo.getApiParamObj().size(); i++) {
                                carStockData.add(carStockInfo.getApiParamObj().get(i));
                                mTv_number.setText(carStockInfo.getApiParamObj().get(i).getNum());
                            }
                        }
                    }
                });
            }
        });
    }

    public void reqCallConfigureInfo() {
        String strURL = String.format(UrlUtils.GET_CAR_CONFIGURE + "&CompanyID=%s", CompanyID);
        volleyRequest(strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                carConfigureInfo = JSON.parseObject(s, CarConfigureInfo.class);
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        carConfigureData = new ArrayList<CarConfigureInfo.ApiParamObjEntity>();
                        if (carConfigureInfo.getApiParamObj().size() != 0) {
                            for (int i = 0; i < carConfigureInfo.getApiParamObj().size(); i++) {
                                carConfigureData.add(carConfigureInfo.getApiParamObj().get(i));
                                mConfDatas.add(carConfigureInfo.getApiParamObj().get(i).getCarConfiguration());
                                mConfigureIdDatas.add(carConfigureInfo.getApiParamObj().get(i).getCarConfigurationID());
                            }

                        }
                    }
                });
            }
        });
    }

    //请求重点库存
    private void reqKeyStockInfo() {
        String strURL = String.format(UrlUtils.GET_KEY_STOCK + "&CompanyID=%s", CompanyID);
        volleyRequest(strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                keyPointStockInfo = JSON.parseObject(s, KeyPointStockInfo.class);
                if (true) {
//                    String json = "[\n" +
//                            "        { \"CarModel\": \"奥迪A6L\", \"CarConfiguration\": \"2016款 TFSI 技术型\", \"CarColor\": \"朱鹭白\", \"Num\": 1 },\n" +
//                            "        { \"CarModel\": \"菲翔\", \"CarConfiguration\": \"1.4T自动悦享版\", \"CarColor\": \"珊瑚红\", \"Num\": 1 },\n" +
//                            "        { \"CarModel\": \"菲翔\", \"CarConfiguration\": \"316i 时尚型\", \"CarColor\": \"中国红\", \"Num\": 6 },\n" +
//                            "        { \"CarModel\": \"菲翔\", \"CarConfiguration\": \"328i M运动型\", \"CarColor\": \"开士米\", \"Num\": 2 },\n" +
//                            "        { \"CarModel\": \"菲翔\", \"CarConfiguration\": \"328i M运动型\", \"CarColor\": \"米兰诺\", \"Num\": 5 },\n" +
//                            "        { \"CarModel\": \"菲悦\", \"CarConfiguration\": \"1.4T自动悦享版\", \"CarColor\": \"尊贵黑\", \"Num\": 1 },\n" +
//                            "        { \"CarModel\": \"辉腾\", \"CarConfiguration\": \"3.0L自动旗舰版\", \"CarColor\": \"典雅黑\", \"Num\": 1 },\n" +
//                            "        { \"CarModel\": \"辉腾\", \"CarConfiguration\": \"3.0L自动旗舰版\", \"CarColor\": \"珍珠白\", \"Num\": 1 },\n" +
//                            "        { \"CarModel\": \"辉腾\", \"CarConfiguration\": \"3.8L手动悦享版\", \"CarColor\": \"奢华银\", \"Num\": 2 },\n" +
//                            "        { \"CarModel\": \"辉腾\", \"CarConfiguration\": \"3.8L手动悦享版\", \"CarColor\": \"珍珠白\", \"Num\": 1 },\n" +
//                            "        { \"CarModel\": \"辉腾\", \"CarConfiguration\": \"3.8L手动悦享版\", \"CarColor\": \"尊贵黑\", \"Num\": 1 }\n" +
//                            "    ]";
                    String json = keyPointStockInfo.getApiParamObj();
                    JSONArray jsonArray = JSON.parseArray(json);
                    Log.v("jsonArray Length", String.valueOf(jsonArray.size()));
                    List<String> carModels = new ArrayList<String>();
                    List<JSONArray> listJSON = new ArrayList<JSONArray>();

                    //CarModel
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject jsonObject = JSON.parseObject(jsonArray.get(i).toString());
                        String carModel = jsonObject.get("CarModel").toString();

                        if (carModels.indexOf(carModel) == -1) {
                            carModels.add(carModel);
                        }
                    }
                    for (int i = 0; i < carModels.size(); i++) {
                        JSONArray jA = new JSONArray();
                        for (int x = 0; x < jsonArray.size(); x++) {
                            JSONObject jsonObject = JSON.parseObject(jsonArray.get(x).toString());
                            String carModel = jsonObject.get("CarModel").toString();
                            if (carModels.get(i).equals(carModel)) {
                                jA.add(jsonObject);
                            }
                        }
                        listJSON.add(jA);
                    }

                    //Fields name
                    String[] fields = new String[]{"配置", "颜色", "数量"};

                    //Screen width
                    DisplayMetrics dm = new DisplayMetrics();
                    getWindowManager().getDefaultDisplay().getMetrics(dm);
                    int screenWidth = dm.widthPixels;
                    int columnWidth = (screenWidth - 0) / 3;

                    LinearLayout body = (LinearLayout) findViewById(R.id.layout_root);
                    for (int i = 0; i < carModels.size(); i++) {
                        //add GridLayout
                        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                        layoutParams.setMargins(0, 20, 0, 20);
                        GridLayout gridLayout = new GridLayout(getApplicationContext());
                        gridLayout.setLayoutParams(layoutParams);
                        gridLayout.setColumnCount(3);
                        gridLayout.setRowCount(3);
                        //title view
                        GridLayout.LayoutParams titleParam = new GridLayout.LayoutParams();
                        titleParam.columnSpec = GridLayout.spec(0, 3);
                        titleParam.setGravity(Gravity.FILL);
                        TextView title = new TextView(getApplicationContext());
                        title.setText(carModels.get(i));
                        title.setLayoutParams(titleParam);
                        title.setTextColor(Color.GRAY);
                        title.setTextSize(15);
                        title.setGravity(Gravity.CENTER);
                        title.setBackgroundResource((R.drawable.table_cell_background));
                        gridLayout.addView(title);

                        //add fields view
                        for (int x = 0; x < fields.length; x++) {
                            GridLayout.LayoutParams fieldParams = new GridLayout.LayoutParams();
                            if (!VersionCheck()) {
                                fieldParams.width = columnWidth;
                            }
                            fieldParams.setGravity(Gravity.FILL);
                            fieldParams.width = columnWidth;
                            TextView textView = new TextView(getApplicationContext());
                            textView.setText(fields[x]);
                            textView.setTextSize(15);
                            textView.setTextColor(Color.GRAY);
                            textView.setBackgroundResource(R.drawable.table_cell_background);
                            textView.setLayoutParams(fieldParams);
                            gridLayout.addView(textView);
                        }

                        //all car below on model
                        JSONArray array = listJSON.get(i);

                        List<JSONArray> list = new ArrayList<JSONArray>();
                        //car configuration collection
                        List<String> carConfigurations = new ArrayList<String>();
                        for (int y = 0; y < array.size(); y++) {
                            JSONObject jsonObject = JSON.parseObject(array.get(y).toString());
                            String configuration = jsonObject.get("CarConfiguration").toString();
                            if (carConfigurations.indexOf(configuration) == -1) {
                                carConfigurations.add(configuration);
                            }
                        }
                        //car configuration include
                        for (int y = 0; y < carConfigurations.size(); y++) {
                            JSONArray jA = new JSONArray();
                            for (int z = 0; z < array.size(); z++) {
                                JSONObject jsonObject = JSON.parseObject(array.get(z).toString());
                                String carConfiguration = jsonObject.get("CarConfiguration").toString();

                                if (carConfigurations.get(y).equals(carConfiguration)) {
                                    jA.add(jsonObject);
                                }
                            }
                            list.add(jA);
                        }

                        for (int y = 0; y < list.size(); y++) {
                            JSONArray carArray = list.get(y);

                            TextView tv = new TextView(getApplicationContext());
                            GridLayout.LayoutParams param = new GridLayout.LayoutParams();
                            param.rowSpec = GridLayout.spec(0, carArray.size());
                            param.setGravity(Gravity.FILL);
                            if (!VersionCheck()) {
                                param.width = columnWidth;
                            }

                            tv.setLayoutParams(param);
                            tv.setText(((JSONObject) carArray.get(0)).get("CarConfiguration").toString());
                            tv.setTextColor(Color.GRAY);
                            tv.setTextSize(15);
                            tv.setGravity(Gravity.CENTER | Gravity.LEFT);
                            tv.setBackgroundResource(R.drawable.table_cell_background);
                            gridLayout.addView(tv);

                            for (int z = 0; z < carArray.size(); z++) {
                                JSONObject object = (JSONObject) carArray.get(z);
                                String[] keys = new String[]{object.get("CarColor").toString(), object.get("Num").toString()};

                                for (int zz = 0; zz < keys.length; zz++) {
                                    GridLayout.LayoutParams params = new GridLayout.LayoutParams();
                                    if (!VersionCheck()) {
                                        params.width = columnWidth;
                                    }
                                    params.setGravity(Gravity.FILL);
                                    TextView textView = new TextView(getApplicationContext());
                                    textView.setText(keys[zz]);
                                    textView.setTextColor(Color.GRAY);
                                    textView.setTextSize(15);
                                    textView.setBackgroundResource(R.drawable.table_cell_background);
                                    textView.setLayoutParams(params);
                                    gridLayout.addView(textView);
                                }

                            }
                        }
                        body.addView(gridLayout);
                    }
                }
            }
        });
    }

    static public boolean VersionCheck() {
        if (Build.VERSION.SDK_INT > 19) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initListener() {
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_Back:
                finish();
                break;
            case R.id.ll_left1:
                finish();
                break;
            case R.id.rl_car_sort:
                /**
                 * 全部车型
                 */
                mTvCar.setTextColor(UIUtils.getColor(R.color.qianlan));
                mIv_icon1.setImageDrawable(UIUtils.getDrawable(R.drawable.upb));
                showCarPopu();
                break;
            case R.id.rl_cus_sort:
                /**
                 * 全部配置
                 */
                mTvCus.setTextColor(UIUtils.getColor(R.color.qianlan));
                mIv_icon2.setImageDrawable(UIUtils.getDrawable(R.drawable.upb));
                showLevPopu();
                break;
            case R.id.rl_time_sort:
                mTvTime.setTextColor(UIUtils.getColor(R.color.qianlan));
                mIv_icon3.setImageDrawable(UIUtils.getDrawable(R.drawable.upb));
                tab1OnClick();
                break;
        }
    }

    private void showLevPopu() {
        ListView mSpListview = initListView2();
        popupConfigure = new PopupWindow(mSpListview, width, ViewGroup.LayoutParams.WRAP_CONTENT);
        //在PopupWindow里面就加上下面代码，让键盘弹出时，不会挡住pop窗口。
        popupConfigure.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        popupConfigure.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popupConfigure.setFocusable(true);
        popupConfigure.setOutsideTouchable(true);//设置点击pw以外的部分，让pw消失
        popupConfigure.setBackgroundDrawable(UIUtils.getDrawable(R.drawable.transparent));
        popupConfigure.showAsDropDown(findViewById(R.id.rl_car_sort));
        popupConfigure.setAnimationStyle(-1);
        //背景变暗
        darkView.startAnimation(animIn);
        darkView.setVisibility(View.VISIBLE);
        darkView.setAlpha(0.5f);
        //添加pop窗口关闭事件
        popupConfigure.setOnDismissListener(new popCarDisListener2());
    }

    private void showCarPopu() {
        ListView mSpListview = initListView1();
        mPwCarModel = new PopupWindow(mSpListview, width, ViewGroup.LayoutParams.WRAP_CONTENT);
        //在PopupWindow里面就加上下面代码，让键盘弹出时，不会挡住pop窗口。
        mPwCarModel.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        mPwCarModel.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        mPwCarModel.setFocusable(true);
        mPwCarModel.setOutsideTouchable(true);//设置点击pw以外的部分，让pw消失
        mPwCarModel.setBackgroundDrawable(UIUtils.getDrawable(R.drawable.transparent));
        mPwCarModel.showAsDropDown(findViewById(R.id.rl_car_sort));
        mPwCarModel.setAnimationStyle(-1);
        //背景变暗
        darkView.startAnimation(animIn);
        darkView.setVisibility(View.VISIBLE);
        darkView.setAlpha(0.5f);
        //添加pop窗口关闭事件
        mPwCarModel.setOnDismissListener(new popCarDisListener1());
    }

    /*
 填充 popuwindow  listview
  */
    private ListView initListView1() {
        lv = new ListView(this);
        lv.setVerticalScrollBarEnabled(false); //设置垂直的滚动条不可用
        lv.setBackgroundResource(R.drawable.listview_background);
        lv.setCacheColorHint(UIUtils.getColor(R.color.base));
//        initListivewData();
//        ArrayAdapter arrayAdapter = new ArrayAdapter(
//                PotentialListAct.this, android.R.layout.simple_list_item_1,
//                mDatas);
//        CarModekAdp adapter = new CarModekAdp(mDatas);

        downListAdapter spinnerAdapter = new downListAdapter(CarTypeStockActivity.this, mDatas);
        lv.setAdapter(spinnerAdapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    //全部车型
                    carModel = "";
                } else {
                    carModel = mDatas.get(position);
                }
                currentCarType = position;
                mTvCar.setText(mDatas.get(position));
                CarModelID = mTypeIdDatas.get(position);
                mPwCarModel.dismiss();
            }
        });
        return lv;
    }

    /*
  填充 popuwindow  listview
   */
    private ListView initListView2() {
        lv = new ListView(this);
        lv.setVerticalScrollBarEnabled(false); //设置垂直的滚动条不可用
        lv.setBackgroundResource(R.drawable.listview_background);
        lv.setCacheColorHint(UIUtils.getColor(R.color.base));
//        initListivewData();
//        ArrayAdapter arrayAdapter = new ArrayAdapter(
//                PotentialListAct.this, android.R.layout.simple_list_item_1,
//                mDatas);
//        CarModekAdp adapter = new CarModekAdp(mDatas);

        downListAdapter spinnerAdapter = new downListAdapter(CarTypeStockActivity.this, mConfDatas);
        lv.setAdapter(spinnerAdapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    //全部车型
                    carConfigure = "";
                } else {
                    carConfigure = mConfDatas.get(position);
                }
                currentCarType = position;
                mTvCus.setText(mConfDatas.get(position));
                CarConfigurationID = mConfigureIdDatas.get(position);
                popupConfigure.dismiss();
            }
        });
        return lv;
    }

    private List<String> mDatas = new ArrayList<String>(Arrays.asList("全部车型"));
    private List<String> mConfDatas = new ArrayList<String>(Arrays.asList("全部配置"));
    private List<String> mTypeIdDatas = new ArrayList<String>(Arrays.asList(""));
    private List<String> mColorIdDatas = new ArrayList<String>(Arrays.asList(""));
    private List<String> mConfigureIdDatas = new ArrayList<String>(Arrays.asList(""));
    private int currentCarType;

    /**
     * 添加新笔记时弹出的popWin关闭的事件，主要是为了将背景透明度改回来
     *
     * @author w.pitt
     */
    class popCarDisListener1 implements PopupWindow.OnDismissListener {
        @Override
        public void onDismiss() {
            darkView.startAnimation(animOut);
            darkView.setVisibility(View.GONE);
            mTvCar.setTextColor(UIUtils.getColor(R.color.font3));
            mIv_icon1.setImageDrawable(UIUtils.getDrawable(R.drawable.icondown));
        }
    }

    class popCarDisListener2 implements PopupWindow.OnDismissListener {
        @Override
        public void onDismiss() {
            darkView.startAnimation(animOut);
            darkView.setVisibility(View.GONE);
            mTvCus.setTextColor(UIUtils.getColor(R.color.font3));
            mIv_icon2.setImageDrawable(UIUtils.getDrawable(R.drawable.icondown));
        }
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }
}
